package com.tjsinfo.tjsoa.bylaws.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.tjsinfo.tjsoa.bylaws.bo.IBylawsBO;
import com.tjsinfo.tjsoa.bylaws.vo.Bylaws;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.workflow.WorkFlowTemplate;

public class TongZhiDaiBanAction extends  Action {

	private IBylawsBO bylawsManager;

	public void setBylawsManager(IBylawsBO bylawsManager){
		this.bylawsManager=bylawsManager;
	}
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)  {
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		List list2 = new ArrayList();
		JSONArray array = new JSONArray();
		List list = workFlowTemplate.selectTask(SessionUser.getUserId(request).toString(), "通知");
		 Comparator comp = new Comparator(){
	          public int compare(Object o1,Object o2) {
	              TaskInstance p1=(TaskInstance)o1;
	              TaskInstance p2=(TaskInstance)o2; 
	             if(p1.getId()<p2.getId())
	                 return 1;
	             else
	                 return 0;
	             }
	        };
	        Collections.sort(list, comp);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			TaskInstance taskInstance = (TaskInstance) iterator.next();
			Long flowid =	taskInstance.getProcessInstance().getId();
			Bylaws bylaws = new Bylaws();
			if(bylawsManager.findByFlowId(Integer.parseInt(flowid.toString())).size() >0)
			{
				bylaws = (Bylaws) bylawsManager.findByFlowId(Integer.parseInt(flowid.toString())).get(0);
				bylaws.setTaskid(taskInstance.getId());
				JSONObject object = new JSONObject();
				try {
					object.put("title", bylaws.getTitle());
					object.put("operate", "<a href='"+basePath+"tjsinfo/tjsoa/bylaws/guizhangzhidushenpi.do?method=kongzhi&id="+bylaws.getId()+"&taskid="+bylaws.getTaskid()+"'>批示</a>");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				array.put(object);
			}
		}
		try {
			response.getWriter().print(array);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  null;
	}
}
